﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;

namespace WBrowser.MY_CODE
{
    public partial class AsynDownloads : Form
    {
        private ManualResetEvent _doneevent = new ManualResetEvent(false);
        private Byte[] _buffer = new Byte[1024];
        private string _url;
        private string _text;
        private string _id;

        public AsynDownloads(string url)
        {
            InitializeComponent();
            _url = url;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (_url == string.Empty || _url == "about:blank")
            {
                MessageBox.Show("Url is empty");
                return;
            }
            richTextBox1.Text = "";
            label1.Text = "Async start " + DateTime.Now.ToString();
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_url);
            req.BeginGetResponse(new AsyncCallback(Respcallback), req);
            _doneevent.WaitOne();

            //After find
            richTextBox1.Text = _text;
            textBox1.Text = _id.ToString();
            label1.Text += " end " + DateTime.Now.ToString();
        }

        //delegate void updateRichTextBoxDelegate(string newtext);
        //private void updateRichTextBox(string newtext)
        //{
        //    if (richTextBox1.InvokeRequired)
        //    {
        //        // this is worker thread
        //        updateRichTextBoxDelegate update = new updateRichTextBoxDelegate(updateRichTextBox);
        //        richTextBox1.Invoke(update, new object[] { newtext });
        //    }
        //    else
        //    {
        //        // this is UI thread
        //        richTextBox1.Text += newtext;
        //    }
        //}

        public void Respcallback(IAsyncResult Ar)
        {
            HttpWebRequest req = (HttpWebRequest)Ar.AsyncState;
            HttpWebResponse resp = null;
            Stream respstream = null;
            try
            {
                resp = (HttpWebResponse)req.EndGetResponse(Ar);
                respstream = resp.GetResponseStream();
                respstream.BeginRead(_buffer, 0, _buffer.Length, new AsyncCallback(ReadCallback), respstream);
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message);
                respstream.Close();
                _doneevent.Set();
            }
        }

        public void ReadCallback(IAsyncResult Ar)
        {
            Stream rs = (Stream)Ar.AsyncState;
            int Read = -1;
            try
            {
                Read = rs.EndRead(Ar);
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message);
                rs.Close();
                _doneevent.Set();
                return;
            }
            
            if (Read > 0)
            {
                // Write To Memorystream
                //_downloadedBytes.Write(_buffer, 0, Read);
                _text = GetStringFromByteArray(_buffer);
                _id = GetIDForum(_text);

                //If find id thread then stop
                if (_id != string.Empty)
                {
                    rs.Close();
                    _doneevent.Set();
                }
                else
                {
                    try
                    {
                        rs.BeginRead(_buffer, 0, _buffer.Length, new AsyncCallback(ReadCallback), rs);
                    }
                    catch (Exception E)
                    {
                        MessageBox.Show(E.Message);
                        rs.Close();
                        _doneevent.Set();
                    }
                }
            }
            else

                if (Read == 0)
                {
                    // No More Data To Read.
                    // Close The Response Stream To Free Up The Connection
                    rs.Close();
                    _doneevent.Set();
                }
        }

        /// <summary>
        /// Get Id 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetIDForum(string url)
        {
            string id = "";
            Regex rx = new Regex(@"newthread.php\?do=newthread&amp;(f=[0-9]+)");
            Match m = rx.Match(url);
            while (m.Success)
            {
                id = m.Value.Replace("newthread.php?do=newthread&amp;f=", "");
                m = m.NextMatch();
            }
            return id;
        }

        /// <summary>
        /// Read text to byte[]
        /// </summary>
        /// <param name="sIn"></param>
        /// <returns></returns>
        public static byte[] GetByteArray(string sIn)
        {
            byte[] oTmp = new byte[sIn.Length];
            for (int i = 0; i < sIn.Length; i++)
            {
                oTmp[i] = (byte)(sIn.Substring(i, 1).ToCharArray(0, 1)[0]);
            }
            return oTmp;
        }


        /// <summary>
        /// Read byte to text
        /// </summary>
        /// <param name="oIn"></param>
        /// <returns></returns>
        public string GetStringFromByteArray(byte[] oIn)
        {
            Encoding enc = Encoding.GetEncoding(1252);  // Windows default Code Page
            Decoder d = Encoding.UTF8.GetDecoder();
            char[] charArray = new char[enc.GetCharCount(oIn, 0, oIn.Length)];
            enc.GetDecoder().GetChars(oIn, 0, oIn.Length, charArray, 0);
            string s = new string(charArray);
            return s;
            
            //string sTmp = "";
            //for (int i = 0; i < oIn.Length; i++)
            //{
            //    if (oIn[i] == 0) break;
            //    sTmp += ((char)oIn[i]).ToString();
            //}
            //return sTmp;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
            if (_url == string.Empty || _url == "about:blank")
            {
                MessageBox.Show("Url is empty");
                return;
            }
            richTextBox1.Text = "";
            label1.Text = "Sync start " + DateTime.Now.ToString();
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_url);
            HttpWebResponse resp = null;
            Stream respstream = null;
            StreamReader rdr = null;
            Encoding enc = Encoding.GetEncoding(1252);  // Windows default Code Page
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
                respstream = resp.GetResponseStream();
                rdr = new StreamReader(resp.GetResponseStream(), enc);
                _text = rdr.ReadToEnd();
                _id = GetIDForum(_text);
                richTextBox1.Text = _text;
                textBox1.Text = _id.ToString();
                respstream.Close();
                rdr.Close();
                label1.Text += " end " + DateTime.Now.ToString();
            }
            catch
            {
                respstream.Close();
            }
            
        }
    }
}
